package nd.android.am;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import nd.android.am.Adapter.Account;
import nd.android.am.Adapter.User;
import nd.android.am.bean.Settlement;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class CalculateService extends Service {
	private static final String TAG = "CalculateService";

	public static final String CALCULATE_ACTION = "nd.android.action.CALCULATE";
	private static final String[] PROJECTION = {
		Account.PAYER,
		Account.USERS,
		Account.AMOUNT
	};
	
	private String result;

	@Override
	public void onCreate() {
		Log.e(TAG, "onCreate");
	}

	@Override
	public void onDestroy() {
		Log.e(TAG, "onDestroy");
		Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.e(TAG, "onStart");
		super.onStart(intent, startId);
		// Toast.makeText(this, R.string.calculate_start,　Toast.LENGTH_SHORT).show();
		calculate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.e(TAG, "onBind");
		return null;
	}

	@Override
	public boolean onUnbind(Intent i) {
		Log.e(TAG, "onUnbind");
		return false;
	}

	@Override
	public void onRebind(Intent i) {
		Log.e(TAG, "onRebind");
	}

	private void calculate() {
		List<String> users = User.getUsers();
		Map<String, Settlement> settles = new LinkedHashMap<String, Settlement>();
		for (String user : users) {
			settles.put(user, new Settlement(user));
		}
		try{
			String where = Account.STATUS + "=" + Account.STATUS_NORMAL;
			Cursor cursor = getContentResolver().query(Account.CONTENT_URI, PROJECTION, where, null, null);
			double totalOutlay = 0;
			if(cursor != null && cursor.getCount() > 0){
	    		cursor.moveToFirst();
				while(!cursor.isAfterLast()){
					String payer = cursor.getString(0);
					Settlement settle = settles.get(payer);
					if(settle == null)
						continue;
					double amount = cursor.getLong(2) / 100d;
					settle.addOutlay(amount);
					totalOutlay += amount;
					String _users = cursor.getString(1);
					String[] us = _users.split(",");
					for (int i = 0; i < us.length; i++) {
						settle = settles.get(us[i]);
						if(settle == null)
							break;
						settle.addConsume(amount / us.length);
					}
					cursor.moveToNext();
				}
			}
			StringBuilder sb = new StringBuilder(getResources().getString(R.string.calculate_stop));
			sb.append(":\n");
			for (Map.Entry<String, Settlement> settle : settles.entrySet()) {
				sb.append(settle.getValue().toString()).append("\n");
			}
			sb.append("\n");
			sb.append("Total:\t").append(Math.floor(totalOutlay * 100) / 100);
			this.result = sb.toString();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			stopSelf();
		}
	}
}
